<template>
	<a-row>
		<h3  v-if='isEdit'>录入订单货物信息</h3>
		<a-button type="primary"  v-if='isEdit'  class='cursor  mt12  w100  mb20'  block  @click='addContact()' ><a-icon type="plus-circle" />添加</a-button>
    	<a-table :columns="columns" :locale="{emptyText: '暂无货物数据'}" :dataSource="bizBankAccounts" bordered  :pagination='false'  :rowKey="record => record.$index"  v-if='columnsRenderer==true' >
    		
		    <template v-for="col in coldata" :slot="col" slot-scope="text, record, index"  >
		      <div :key="col"   > 
		      	<template  v-if="record.editable"   >

		      		<a-radio-group   v-if="col=='moreLess'"  :value="record.moreLess"   @change="e => handleChangeContact(e.target.value, col, index)" > 
				      <a-radio value="1">是</a-radio> 
				      <a-radio value="0">否</a-radio> 
				    </a-radio-group>
				    <a-select  :value="text"   v-else-if="col.indexOf('unitPriceUnit')!=-1"     @change="e => handleChangeContact(e , col, index)" >  
                        <a-select-option value="1">USD</a-select-option>
                        <a-select-option value="2">GBP</a-select-option>
                        <a-select-option value="3">EUR</a-select-option>
                        <a-select-option value="4">HKD</a-select-option>
                        <a-select-option value="5">CNY</a-select-option>
                    </a-select> 
                    <a-textarea
			          v-else
			          style="margin: -5px 0"
			          :value="text"
			          autosize 
			          @change="e => handleChangeContact(e.target.value, col, index)"
			        /> 
		      	</template>  
		        <template v-else>
		        	<span  v-if='col=="moreLess"'>{{text | commonRadio}}</span>
		        	<span  v-else-if='col.indexOf("unitPriceUnit")!=-1'>{{text | moneyUnit}}</span>
		        	<span  v-else>{{text}}</span>
		        </template>
		      </div>
		    </template>
		    
		    <template slot="operation" slot-scope="text, record, index"  v-if='isEdit'>
		      <div class='editable-row-operations'>
		        <span v-if="record.editable">
		        	<template  v-if='record.add'>
		        		<span  class='color-blue cursor'  @click="() => addNewContact(index)">添加</span>
		        		<a-divider type="vertical" /> 
				        <span  class='color-red cursor' @click='cancelContact_add(index)'>取消</span>
		        	</template>
		          	<template  v-else>
		          		<a  @click="() => saveContact(index)"  class='color-blue'>保存</a>
		          		<a-divider type="vertical" /> 
				        <a  class='color-red' @click='cancelContact(index)'>取消</a> 
		          	</template>
		        </span>
		        <span v-else>
		          <a @click="() => editContact(index,record)"  class='color-blue'>编辑</a>
		          <a-divider type="vertical" />
		          <a-popconfirm title='确认删除该条数据?' @confirm="() => delContact(record.code,index)" okText='确认' cancelText='取消'>
		            <a  class='color-red'>删除</a>
		          </a-popconfirm>
		        </span>

		      </div>
		    </template>
		</a-table>
		<a-row  class='mt28'  v-if='isEdit'>
			<!-- 合同=》货单 -->
			<span   v-if='contractModal==true'> 
		        <router-link :to="{path:'/order/detail#2',query:{code:orderCode}}"><a-button  >返回</a-button></router-link>
		        <a-button  @click='contractTypeVisible=true' >生成合同</a-button>
	        </span>
	        <!-- 列表录入=》货单 -->
	        <span  v-else>
	        	<router-link to='/order'> <a-button  class='mr20'> 返回 </a-button></router-link>   
	        </span>
	    </a-row>
	    <!-- 详情=》货单 -->
	    <a-row  class='mt28'   v-if='isEdit == false'>
	    	<router-link :to="{path:'/order/detail',query:{code:orderCode}}"> <a-button  class='mr20'> 返回订单 </a-button></router-link>  
	    	 <a-button  class='mr20'  @click='isEdit = true'> <a-icon type="form" />编辑 </a-button>  
	    </a-row>
	    <a-modal title="选择生成合同类型" ref='contractTypeModal'  :visible="contractTypeVisible"  @ok="produceContract"   @cancel='contractTypeVisible=false'  okText="确定" cancelText="取消">
			<p>请选择生成合同类型：<a-select   style="width: 120px" v-model='produceType'>
					      <a-select-option    value='1'>普通合同</a-select-option> 
					      <a-select-option    value='2'>国际贸易合同</a-select-option>  
					    </a-select>
			</p>
	    </a-modal>
	</a-row>

</template>
<script>
import  {  submitGoods,detailOrder,modifyGoods,getGoodsListOforder,getContractCode,produce_Contract,delGood  }  from  '@/api/order/index'

	export default{
		name:'cargoAdd',
		data(){
			return {
				bizBankAccounts:[],/*银行表 data*/
				cacheData:[],
				columns:[
					{
					  title: '商品名称',
					  dataIndex: 'name',
					  width: '12%',
					  scopedSlots: { customRender: 'name' },
					}, {
					  title: '规格/型号',
					  dataIndex: 'model', 
					  width: '8%',
					  scopedSlots: { customRender: 'model' },
					}, {
					  title: '数量',
					  dataIndex: 'goodsNum',
					  width: '9%',
					  scopedSlots: { customRender: 'goodsNum' }, 
					},
					 {
					  title: '溢短装',
					  dataIndex: 'moreLess', 
					  width: '6%',
					  scopedSlots: { customRender: 'moreLess' },
					},  
					{
					      title: '单价', 
					      width:'30%',
					      children: [
					         
					       ]
					},
					{
					  title: 'hs编码',
					  dataIndex: 'hsCode', 
					  width: '9%',
					  scopedSlots: { customRender: 'hsCode' },
					}, 
					{
					  title: '退税税率',
					  dataIndex: 'taxRebateRate',
					  width: '6%',
					  scopedSlots: { customRender: 'taxRebateRate' }, 
					}, 
					{
					  title: '申报单位',
					  dataIndex: 'goodsUnit',
					  width: '6%',
					  scopedSlots: { customRender: 'goodsUnit' }, 
					},    
					{
					  title: '操作',
					  dataIndex: 'operation',
					  width: '10%',
					  scopedSlots: { customRender: 'operation' },
				}],
				orderCode:'',
				transactionCode:'',
				contractModal:false,//当前是否为合同模式

				currentPriceLen:null,/*交易条数记录*/
				coldata:['name', 'model', 'goodsNum','moreLess','hsCode','taxRebateRate','goodsUnit'],//新增时需要添加的表头显示
				columnsRenderer:false,//columns 控制渲染
				testarr:[],
				transactionVOList:[],//交易记录双方记录
				isEdit:true,

				contractTypeVisible:false,//合同modal
				modifyContract:false,
				produceType:'1',//生成合同类型
				contract_Code:'',//合同code
			}
		},
		created(){
			this.orderCode = this.$route.query.code  
			//查看页
			if(this.$route.hash.slice(1) == 1){
				this.isEdit = false
			}  
			//生成合同页，仅显示双方的价格
			if(this.$route.query.transactionCode){
				this.transactionCode = this.$route.query.transactionCode
				this.contractModal = true
			}
			//生成合同时，走修改路径
			if(this.$route.query.isEdit){
				this.modifyContract = true
			}
			this.pageInit()
		},
		methods:{
			pageInit(){
				detailOrder(this.orderCode).then((res)=>{
					if(res.data.flag == true){
						let data = res.data.data
						/*交易条数记录*/
						this.currentPriceLen = data.transactionVOList.length
						this.transactionVOList = data.transactionVOList
						/*由交易记录双方=》col*/
						//交易模式为false
						if(this.contractModal == false){
							data.transactionVOList.forEach((item,index)=>{  
								this.columns[4].children.push({
								  title: item.entList[0].name+'-'+item.entList[1].name,
								  // dataIndex: 'unitPrice'+index, 
								  // scopedSlots: { customRender: 'unitPrice'+index },
								  children:[
								  		{title:'价格',dataIndex:'unitPrice'+index,width:'9%',scopedSlots: { customRender: 'unitPrice'+index },},
								  		{title:'单位',dataIndex:'unitPriceUnit'+index, scopedSlots: { customRender: 'unitPriceUnit'+index },},
								  ]
								})
								this.coldata.push('unitPrice'+index)
								this.coldata.push('unitPriceUnit'+index)
							})
							this.columnsRenderer = true
						}
						if(this.contractModal == true){
							
							data.transactionVOList.forEach((item,index)=>{  
								if(item.code == this.transactionCode){

									  this.columns[4].children.push({
									  title: item.entList[0].name+'-'+item.entList[1].name,
									  // dataIndex: 'unitPrice'+index, 
									  // scopedSlots: { customRender: 'unitPrice'+index },
									  children:[
									  		{title:'价格',dataIndex:'unitPrice'+index,scopedSlots: { customRender: 'unitPrice'+index },},
									  		{title:'单位',dataIndex:'unitPriceUnit'+index,width:'9%', scopedSlots: { customRender: 'unitPriceUnit'+index },},
									  ]
									})
									this.coldata.push('unitPrice'+index)
									this.coldata.push('unitPriceUnit'+index)
								}
								
							})
							this.columnsRenderer = true
						}

						
						data.goodsVOList.forEach((item,index)=>{
							item.goodsPriceVOList.forEach((it,ind)=>{
								item['unitPrice'+ind] = it.price
								item['unitPriceUnit'+ind] = it.priceType
							})
						})
						this.bizBankAccounts = data.goodsVOList
						this.cacheData = this.bizBankAccounts.map(item => ({ ...item }));
						console.log(this.columns)
					}
				})
			},
			getGoodsList(){
				getGoodsListOforder({orderCode:this.orderCode,pageSize:100}).then((res)=>{
						if(res.data.flag == true){
							let data = res.data.dataList
							data.forEach((item,index)=>{
								item.goodsPriceVOList.forEach((it,ind)=>{
									item['unitPrice'+ind] = it.price
									item['unitPriceUnit'+ind] = it.priceType
								})
							})
							this.bizBankAccounts = data
							this.cacheData = this.bizBankAccounts.map(item => ({ ...item }));
						}
				})
			},

			 	// 联系人表格
		    addContact () { 
			    this.count = this.bizBankAccounts.length
			      let newData  = {
			      		editable:true,
			      		add:true,
				        name:'',
				        model: '',
				        goodsNum: '',
				        moreLess: '', 

				        hsCode:'',
				        taxRebateRate:'',
				        goodsUnit:'',
			      }
			       
			      for(let i=0;i<this.currentPriceLen;i++){
			      	newData['unitPrice'+i] ='' 
			      	newData['unitPriceUnit'+i] ='1' 
			      }
			      console.log(newData)
			      this.bizBankAccounts = [newData,...this.bizBankAccounts]
			      this.cacheData = this.bizBankAccounts.map(item => ({ ...item }));
		    }, 
		    saveCurrent(num){
	    		this.$router.push('/order/detail')
	    	},
		    /*联系人值改变，更新data*/
		    handleChangeContact (value, column,index) {
				const newData = [...this.bizBankAccounts]
				// console.log(value, column,index)
				// const target = newData.filter(item => key === item.key)[0]
				// console.log(index,newData.filter((item,ind) => index === ind))
				const target = newData.filter((item,ind) => index === ind)[0]

				if (target) {
				target[column] = value 
				this.bizBankAccounts = newData
				} 
		    },

		    editContact (index,record) {
		    	console.log(record)
		      const newData = [...this.bizBankAccounts]
		      const target = newData.filter((item,ind) => index === ind)[0]
		      if (target) {
		        target.editable = true
		        target.code = record.code
		        this.bizBankAccounts = newData//更新data中列的可编辑状态
		        // console.log(this.bizBankAccounts)
		      }
		    },
		    saveContact ( index) {
		      const newData = [...this.bizBankAccounts]
		      const target = newData.filter((item,ind) => index === ind)[0]
		      if (target) {
		        delete target.editable
		        this.bizBankAccounts = newData
		        this.cacheData = newData.map(item => ({ ...item }))
		      }
		      target.goodsPriceVOList = this.transactionVOList.map((item,index)=>{
					return {
						buyer:item.buyer,
						seller:item.seller,
						price:target['unitPrice'+index],
						priceType:target['unitPriceUnit'+index],
					}
				}) 
		      console.log(target)
				if(target){
				 //    delete target.editable
					// delete target.add
					modifyGoods(target).then((res)=>{
						// this.$message.success(res.data.msg)
					})
				}
		    },
		    addNewContact(index){
		    	const newData = [...this.bizBankAccounts]
				const target = newData.filter((item,ind) => index === ind)[0]
				if (target) {
					// if(target.accountName =='' && target.bankAccount =='' && target.bankAddress == ''  &&  target.bankName==''  &&  target.swift == ''){
					// 	return this.$message.warning('请输入信息！');
					// }
					delete target.editable
					delete target.add
					this.bizBankAccounts = newData
					this.cacheData = newData.map(item => ({ ...item }))
				}
				
				target.orderCode = this.orderCode 
				console.log(target)
				// console.log(this.transactionVOList)
				target.goodsPriceVOList = this.transactionVOList.map((item,index)=>{
					return {
						buyer:item.buyer,
						seller:item.seller,
						price:target['unitPrice'+index],
						priceType:target['unitPriceUnit'+index],
					}
				}) 
				if(target){
				 //    delete target.editable
					// delete target.add
					submitGoods(target).then((res)=>{
						if(res.data.flag == true){
							this.$message.success(res.data.msg)
							this.getGoodsList()
						}

						
					})
				}

		    },
		    cancelContact (index) { 
		      const newData = [...this.bizBankAccounts]
		      // console.log(newData)
		      const target = newData.filter((item,ind) => index === ind)[0]
		      // console.log(this.cacheData)
		      if (target) {
		        Object.assign(target, this.cacheData.filter((item,ind1) => index === ind1)[0])
		        delete target.editable
		        this.bizBankAccounts = newData
		      }
		    },
		    cancelContact_add(index){
		    	const dataSource = [...this.bizBankAccounts]
		      	this.bizBankAccounts = dataSource.filter((item,ind) => ind !== index)
		    },
		    delContact(code,index){
		    	delGood(code).then((res)=>{
		    		if(res.data.flag == true){
		    			this.$message.success(res.data.msg)
		    			const dataSource = [...this.bizBankAccounts]
		      			this.bizBankAccounts = dataSource.filter((item,ind) => ind !== index)
		    		}
		    	})
		      
		    },
		    produceContract(){
		    	//根据交易获得合同code 
		    	let contractCode = new Promise((resolve,reject)=>{
		    		// console.log(this.transactionCode)
		    		getContractCode(this.transactionCode).then((res)=>{
		    			if(res.data.flag == true){
		    				resolve(res.data.data)
		    			}
		    			else{
		    				reject()
		    			}
		    		})
		    	})
		    	function produceContract(contract_Code,produceType){
		    		return new Promise((resolve,reject)=>{
					    produce_Contract(contract_Code,produceType).then((res)=>{
				    			if(res.data.flag == true){
				    				resolve(res.data.msg)
				    			}
				    			else{
				    				reject()
				    			}
				    		})
				    	})
		    	} 
				
		    	//生成合同
		    	contractCode.then((result)=>{
		    		this.contract_Code = result.code
		    		produceContract(this.contract_Code,this.produceType).then((res)=>{
		    			this.$message.success(res)
		    			this.contractTypeVisible = false
		    			this.$router.push({path:'/order/detail',query:{code:this.orderCode}})
		    		})
		    	}).catch((error)=>{
		    		this.$message.error('请求有误，请稍后尝试')
		    	})
		    },

			}
	}
</script>

<style scoped="='scoped">
	
</style>